package com.yyfax.common.form;

import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.yyfax.common.CLog;
import com.yyfax.common.R;
import com.yyfax.common.toast.CompatToast;
import com.yyfax.common.tools.DensityUtil;

import java.lang.reflect.Constructor;

/**
 * Created by fuqiang on 2017/4/28.
 * 自定义表单类，左边是textview，右边是edittext或者textview
 * Copyright  2017 www.yylending.com. All Rights Reserved.
 */
public class FormRow extends LinearLayout {
    private static final String TAG = "FormRow";

    /**
     * 左边textview的颜色
     */
    private ColorStateList mLeftTextColor;

    /**
     * 左边的textView
     */
    protected TextView mLeftTextView;

    /**
     * 左边textview的宽度
     */
    private int mLeftWidth;

    /**
     * 自定义属性
     */
    private TypedArray mTa;

    /**
     * 普通输入框校验的处理者
     */
    private FormRowControl mNormalControl;

	/**
	 * 带右边按钮普通输入框校验的处理者
	 */
	private FormRowControl mNormalWithDrawableRIghtControl;

    /**
     * 下拉选择框校验的处理者
     */
    private FormRowControl mSelectControl;

    /**
     * 公司座机校验的处理者
     */
    private FormRowControl mLandlineControl;

    /**
     * 身份证校验的处理者
     */
    private FormRowControl mIdCardControl;

    /**
     * 手机号码校验的处理者
     */
    private FormRowControl mPhoneControl;

    /**
     * 银行卡校验的处理者
     */
    private FormRowControl mBankCardControl;

    /**
     * 金额校验的处理者
     */
    private FormRowControl mAmountControl;

    /**
     * 配置的表单的类型
     */
    private int mType;

    /**
     * 反馈的提示信息
     */
    public NoticeText noticeText;

    /**
     * 带删除图标的EditText
     */
    public ClearEditText mClearEditText;

    /**
     * 选择文本表单
     */
    public FormSelectView mFormSelectView;

    /**
     * 带扫描按钮的输入框
     */
    public FormInputView mFormInputView;

    /**
     * 座机输入框
     */
    public FormLandLineView mFormLandLineView;
	private boolean mCanEdit = true;//能否编辑身份证

    public FormRow(Context context) {
        super(context);
    }

    public FormRow(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public FormRow(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        setOrientation(LinearLayout.HORIZONTAL);
        ClassTypeSingleton.getSingleton();
        noticeText = new NoticeText();
        mTa = context.obtainStyledAttributes(attrs, R.styleable.FormRow);
        mType = mTa.getInt(R.styleable.FormRow_customType, 3);

        //根据配置得到反馈的提示语
        String emptyFormat = mTa.getString(R.styleable.FormRow_emptyFormat);
        String emptyKeyword = mTa.getString(R.styleable.FormRow_emptyKeyword);
        //内容为空时的提示内容，"xxx不能为空"，在XML文件中配置提示的关键字
        if (emptyFormat != null) {
            noticeText.mEmptyMsg = String.format(emptyFormat, emptyKeyword);
        }
        String expressionFormat = mTa.getString(R.styleable.FormRow_expressionFormat);
        String expressionKeyword = mTa.getString(R.styleable.FormRow_expressionKeyword);
        //内容格式错误时的提示内容，"xxx不能为空"，在XML文件中配置提示的关键字
        if (expressionFormat != null) {
            noticeText.mExpressionMsg = String.format(expressionFormat, expressionKeyword);
        }

        noticeText.mOverRangeMsg = mTa.getString(R.styleable.FormRow_overRange);
        noticeText.mAmountMsg = mTa.getString(R.styleable.FormRow_amount);

        mLeftWidth = mTa.getDimensionPixelSize(R.styleable.FormRow_leftWidth, DensityUtil.dip2px(100 - 14));
        //字体大小，左边和右边的textview一样
        float mTextSize = mTa.getDimension(R.styleable.FormRow_leftTextSize, DensityUtil.sp2px(getContext(), 15));//设置textsize
        mLeftTextView = new TextView(context);
        mLeftTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTextSize);
        mLeftTextColor = mTa.getColorStateList(R.styleable.FormRow_leftTextColor);//设置textcolor
        if (mLeftTextColor != null)
            mLeftTextView.setTextColor(mLeftTextColor);
        else
            mLeftTextView.setTextColor(getResources().getColor(R.color.color_333333));
        mLeftTextView.setGravity(Gravity.CENTER_VERTICAL);
        mLeftTextView.setText(mTa.getString(R.styleable.FormRow_leftText));//设置text
        addView(mLeftTextView);

        //根据type来动态add右边的view
        String className = ClassTypeSingleton.getSingleton().getClassNames().get(mType);
        if (className != null) {
            try {
                Class clazz = Class.forName(className);
                Constructor constructor = clazz.getConstructor(Context.class, AttributeSet.class);
                if (className.contains("ClearEditText")) {
                    mClearEditText = (ClearEditText) constructor.newInstance(context, attrs);
                    mClearEditText.setSingleLine(true);
                    mClearEditText.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTa.getDimension(R.styleable.FormRow_textSize, DensityUtil.sp2px(getContext(), 15)));//设置textsize

                    addView(mClearEditText);
                } else if (className.contains("FormSelectView")) {
                    mFormSelectView = (FormSelectView) constructor.newInstance(context, attrs);
                    addView(mFormSelectView);
                } else if (className.contains("FormInputView")) {
                    mFormInputView = (FormInputView) constructor.newInstance(context, attrs);
                    addView(mFormInputView);
                } else if (className.contains("FormLandLineView")) {
                    mFormLandLineView = (FormLandLineView) constructor.newInstance(context, attrs);
                    addView(mFormLandLineView);
                }

            } catch (Exception e) {
                //e.printStackTrace();
                CLog.e(TAG, e.toString());
            }
            mNormalControl = new NormalControl();
			mNormalWithDrawableRIghtControl = new NormalWithDrawableRightControl();
            mSelectControl = new SelectControl();
            mLandlineControl = new LandLineControl();
            mIdCardControl = new IdCardControl();
            mPhoneControl = new PhoneControl();
            mBankCardControl = new BankCardControl();
            mAmountControl = new AmountControl();
            mNormalControl.setFormRowControl(mNormalWithDrawableRIghtControl);
			mNormalWithDrawableRIghtControl.setFormRowControl(mSelectControl);
            mSelectControl.setFormRowControl(mLandlineControl);
            mLandlineControl.setFormRowControl(mIdCardControl);
            mIdCardControl.setFormRowControl(mPhoneControl);
            mPhoneControl.setFormRowControl(mBankCardControl);
            mBankCardControl.setFormRowControl(mAmountControl);
        }
        mTa.recycle();
    }

    /**
     * 释放内存,建议在退出应用或者不再使用该view时使用
     */
    public void destory() {
        mNormalControl = null;
		mNormalWithDrawableRIghtControl = null;
        mSelectControl = null;
        mLandlineControl = null;
        mIdCardControl = null;
        mPhoneControl = null;
        mBankCardControl = null;
        mAmountControl = null;
    }

    /**
     * 合法性检查
     */
    public boolean validate() {
        if (mNormalControl != null) {
            return mNormalControl.toastControl(mType, this, noticeText);
        }
		CompatToast.showShortToast(getContext().getApplicationContext(), R.string.unknown_error);
		return false;
    }

    /**
     * 根据配置获取FormRow右边的View
     */
    public View getRightView() {
        switch (mType) {
            case 3:
            case 8:
            case 10:
                return mClearEditText;
            case 4:
            case 5:
                return mFormSelectView;
            case 7:
            case 9:
            case 11:
                return mFormInputView;
            case 6:
                return mFormLandLineView;
        }
        return null;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        View leftChild = getChildAt(0);
        leftChild.measure(MeasureSpec.makeMeasureSpec(mLeftWidth, MeasureSpec.EXACTLY), heightMeasureSpec);
        int mRightWidth = MeasureSpec.getSize(widthMeasureSpec) - mLeftWidth;

        View rightChild = getChildAt(1);
        if (rightChild != null)
            rightChild.measure(MeasureSpec.makeMeasureSpec(mRightWidth, MeasureSpec.EXACTLY), heightMeasureSpec);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP)
            CLog.i(TAG, "MotionEvent.ACTION_UP");
        return super.onTouchEvent(event);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        int childCount = getChildCount();
        View childView0 = getChildAt(0);
        View childView1 = getChildAt(1);

        childView1.layout(l + childView0.getMeasuredWidth(), childView0.getTop(), l + childView0.getMeasuredWidth() + childView1.getMeasuredWidth(), childView0.getBottom());

//        int mTotalLength = getPaddingLeft()+l;
//        for (int i = 0; i < childCount; i++) {
//            View childView = getChildAt(i);
//            int measureHeight = childView.getMeasuredHeight();
//            int measureWidth = childView.getMeasuredWidth();
//            childView.layout(mTotalLength, t, mTotalLength+measureWidth, b);
//            mTotalLength+= measureWidth;
//        }
    }

    /**
     * 设置文本
     */
    public void setText(CharSequence text) {
        switch (mType) {
            case 3:
            case 8:
            case 10:
                mClearEditText.setText(text);
                break;
            case 4:
            case 5:
                mFormSelectView.setText(text);
                break;
            case 7:
            case 9:
			case 11:
                mFormInputView.setText(text);
                break;
        }
    }

    /**
     * 获取文本
     */
    public String getText() {
        switch (mType) {
            case 3:
            case 8:
            case 10:
                return mClearEditText.getFormText();
            case 4:
            case 5:
                return mFormSelectView.getFormText();
            case 7:
            case 9:
			case 11:
                return mFormInputView.getFormText();
        }
        return null;
    }

	/**
	 * Set the visibility state of this view.
	 *
	 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
	 * @attr ref android.R.styleable#View_visibility
	 */
	@Override
	public void setVisibility(int visibility) {
		super.setVisibility(visibility);
		if(mLeftTextView != null){
			mLeftTextView.setVisibility(visibility);
		}
		View right = getRightView();
		if(right != null){
			right.setVisibility(visibility);
		}
	}
	//如果edittext不能编辑，则在外面拦截点击事件
	@Override
	public boolean onInterceptTouchEvent(MotionEvent ev) {
		if (!mCanEdit)
			return true;
		return super.onInterceptTouchEvent(ev);
	}

	public void setmCanEdit(boolean mCanEdit) {
		this.mCanEdit = mCanEdit;
	}
}
